package com.shenglaotuan.community.common.interceptor;

import com.shenglaotuan.community.common.entity.JwtConfig;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.SignatureException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import sun.rmi.runtime.Log;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private JwtConfig jwtConfig;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws SignatureException {
        if("OPTIONS".equals(request.getMethod())){
            System.err.println("OPTIONS");
            return false;
        }
        /** Token 验证 */
        String token = request.getHeader(jwtConfig.getHeader());
        if (StringUtils.isEmpty(token)) {
            token = request.getParameter(jwtConfig.getHeader());
        }
        if (StringUtils.isEmpty(token)) {
            throw new SignatureException(jwtConfig.getHeader() + "不能为空");
        }

        Claims claims = null;
        try {
            claims = jwtConfig.getTokenClaim(token);
            if (claims == null || jwtConfig.isTokenExpired(claims.getExpiration())) {
                throw new SignatureException("登录已过期，请重新登录！");
            }
        } catch (Exception e) {
            throw new SignatureException("登录已过期，请重新登录！");
        }

        String oldToken = (String) redisTemplate.opsForValue().get("token-" + claims.getSubject());
        if(StringUtils.isEmpty(oldToken)){
            throw new SignatureException("登录已过期，请重新登录！");
        }
        // 判断两个token的randomId是否不一致
        if(!jwtConfig.getTokenClaim(oldToken).get("randomId").equals(claims.get("randomId"))){
            throw new SignatureException("登录已过期，请重新登录！");
        }

        // 将uid加入参数中
        request.setAttribute("uid", claims.getSubject());

        return true;
    }
}
